package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.RequisitionSimpleOriginal;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: HuXiaoDan
 * 创建时间: 2017/4/21 15:21
 */
public class CheckOutMainFragment extends Fragment {
  protected static final String EXTRA_CONTENT =
      "com.isunland.managesystem.ui.CheckOutMainFragment.EXTRA_CONTENT";
  protected static final String EXTRA_FROM =
      "com.isunland.managesystem.ui.CheckOutMainFragment.EXTRA_FROM";
  protected static final String EXTRA_IFALLOWSUPPLEMENT =
      "com.isunland.managesystem.ui.CheckOutMainFragment.EXTRA_IFALLOWSUPPLEMENT";

  protected static final int ADD = 1;
  protected static final int EDIT = 2;
  protected static final int WAIT_CHECK = 3;// 审核中
  protected static final int CHECK_PASS = 4;// 已审核
  public static final int REQUEST_DELETE = 5;
  public static final int REQUEST_SUBMIT = 6;
  protected static final String TYPE_SAVE = "save";
  protected static final String TYPE_RUN = "run";
  protected static final String OUT = "out";
  protected static final String OVER = "over";

  private EditText metMianReasonCheckOver;
  private TextView mtvRegStaffNameCheckOver;
  private TextView mtvRegDateCheckOver;
  private TextView mtvDeptCheckOver;
  private RadioGroup mRgOut;

  private BaseVolleyActivity mActivity;
  private CurrentUser mUser;
  private RequisitionSimpleOriginal mcontent;
  private boolean isSave;//主表时不是保存成功,默认false,保存成功true
  private int mMenuType;
  private String mId;
  private String mFrom;//新加班over,新外出out
  private String mIfAllowSupplement;//外出是否允许补填
  private String mIfLaterWriter = "F";//是否补填，T为补填外出，F为申请外出
  private CallBack mcallBack;

  //回调接口
  public interface CallBack {
    void onRefresh(String pid, String ifLaterWriter);
  }

  @Override public void onAttach(Activity activity) {
    super.onAttach(activity);
    mcallBack = (CallBack) getActivity();
  }

  @Override public void onDetach() {
    super.onDetach();
    mcallBack = null;
  }

  @Override public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setDisplayHomeAsUpEnabled(true);
    }
    isSave = false;
    mUser = CurrentUser.newInstance(getActivity());
    mcontent = (RequisitionSimpleOriginal) getArguments().getSerializable(EXTRA_CONTENT);
    mFrom = getArguments().getString(EXTRA_FROM);

    if (mcontent != null) {
      mId = mcontent.getId();
      String mDataStatus = mcontent.getDataStatus();
      if (null != mDataStatus && mDataStatus.equalsIgnoreCase("checkPass")) {
        mMenuType = CHECK_PASS;
      } else if (null != mDataStatus && mDataStatus.equalsIgnoreCase("waitCheck")) {
        mMenuType = WAIT_CHECK;
      } else {
        mMenuType = EDIT;
      }
    } else {
      mId = UUID.randomUUID().toString();
      mMenuType = ADD;
    }

    if (mcontent == null && OUT.equalsIgnoreCase(mFrom)) {
      //添加外出
      mIfLaterWriter = "F";
      mIfAllowSupplement = getArguments().getString(EXTRA_IFALLOWSUPPLEMENT);
    }
    if (mcontent != null && OUT.equalsIgnoreCase(mFrom)) {
      //详情外出
      mIfAllowSupplement = mcontent.getIfAllowSupplement();
      if ("T".equalsIgnoreCase(mIfAllowSupplement)) {
        mIfLaterWriter = mcontent.getIfLaterWrite();
      }
      if ("F".equalsIgnoreCase(mIfAllowSupplement)) {
        mIfLaterWriter = "F";
      }
    }
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_check_out_main, container, false);
    findViews(view);
    initData();
    return view;
  }

  private void findViews(View view) {
    metMianReasonCheckOver = (EditText) view.findViewById(R.id.et_mianReason_checkOver);
    mtvRegStaffNameCheckOver = (TextView) view.findViewById(R.id.tv_regStaffName_checkOver);
    mtvRegDateCheckOver = (TextView) view.findViewById(R.id.tv_regDate_checkOver);
    mtvDeptCheckOver = (TextView) view.findViewById(R.id.tv_dept_checkOver);
    mRgOut = (RadioGroup) view.findViewById(R.id.rg_type);
    TextView mLine = (TextView) view.findViewById(R.id.ll_line);
    RadioButton mRbApplyOut = (RadioButton) view.findViewById(R.id.rb_apply);
    RadioButton mRbSupplyOut = (RadioButton) view.findViewById(R.id.rb_supply);
    mRbApplyOut.setText(R.string.applyOut);
    mRbSupplyOut.setText(R.string.supplyOut);
    //如果是加班主表隐藏 RadioButton,外出就显示
    if (OVER.equalsIgnoreCase(mFrom)) {
      //加班
      mRgOut.setVisibility(View.GONE);
      mLine.setVisibility(View.VISIBLE);
    }
    if (OUT.equalsIgnoreCase(mFrom)) {
      //外出
      if ("T".equalsIgnoreCase(mIfAllowSupplement)) {
        //允许补填
        mRgOut.setVisibility(View.VISIBLE);
        mLine.setVisibility(View.GONE);
        if ("T".equalsIgnoreCase(mIfLaterWriter)) {
          mRbSupplyOut.setChecked(true);
        }
        if ("F".equalsIgnoreCase(mIfLaterWriter)) {
          mRbApplyOut.setChecked(true);
        }
      }
      if ("F".equalsIgnoreCase(mIfAllowSupplement)) {
        //不能允许补填,只可以申请
        mRgOut.setVisibility(View.GONE);
        mLine.setVisibility(View.VISIBLE);
      }
    }

    if (mMenuType == CHECK_PASS || mMenuType == WAIT_CHECK) {
      metMianReasonCheckOver.setEnabled(false);
      mRbSupplyOut.setEnabled(false);
      mRbApplyOut.setEnabled(false);
    }
    mRgOut.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
      @Override public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
        switch (checkedId) {
          //申请
          case R.id.rb_apply:
            mIfLaterWriter = "F";
            break;
          //补填
          case R.id.rb_supply:
            mIfLaterWriter = "T";
            break;
          default:
            break;
        }
      }
    });
  }

  private void initData() {
    if (mcontent != null) {
      metMianReasonCheckOver.setText(mcontent.getTitle());
      mtvRegStaffNameCheckOver.setText(mcontent.getRegStaffName());
      mtvRegDateCheckOver.setText(mcontent.getRegDate());
      mtvDeptCheckOver.setText(mcontent.getDeptName());
    } else {
      mtvRegStaffNameCheckOver.setText(mUser.getRealName());
      mtvRegDateCheckOver.setText(DateUtil.dateToString(new Date(), DateUtil.TYPE_DATE));
      mtvDeptCheckOver.setText(mUser.getDeptName());
    }
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    switch (mMenuType) {
      case ADD:
        inflater.inflate(R.menu.menu_save_submit, menu);
        break;
      case EDIT:
        inflater.inflate(R.menu.menu_save_submit_delete, menu);
        break;
      case WAIT_CHECK:
        inflater.inflate(R.menu.menu_stop, menu);
        break;
      case CHECK_PASS:

        break;

      default:
        break;
    }

    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        return true;
      case R.id.menu_item_save:

        //                if (!isSave) {
        //                    主表未保存
        //                if (isCorrectInput()) {
        //                    volleyPostSave(TYPE_SAVE);
        //                }
        //                } else {
        //                    //主表保存成功
        //                    ToastUtil.show(R.string.is_save);
        //                }

        if (OVER.equalsIgnoreCase(mFrom)) {
          if (isCorrectInput()) {
            volleyPostSave(TYPE_SAVE);
          }
        }
        if (OUT.equalsIgnoreCase(mFrom)) {
          if (!isSave) {
            //                    主表未保存
            if (isCorrectInput()) {
              volleyPostSave(TYPE_SAVE);
            }
          } else {
            //主表保存成功
            ToastUtil.show(R.string.is_save);
          }
        }
        return true;
      case R.id.menu_item_submit:
        boolean isCorrectSubmit = isCorrectInput();
        if (isCorrectSubmit) {
          showDialog(REQUEST_SUBMIT);
        }

        return true;
      case R.id.menu_item_delete:
        showDialog(REQUEST_DELETE);
        return true;

      // 终止流程
      case R.id.menu_item_stop:
        interruptProcess();
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void showDialog(int type) {

    DialogFragment dialog;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (type) {
      case REQUEST_SUBMIT:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.start_up_hint);
        break;
      case REQUEST_DELETE:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);

        break;
      default:
        return;
    }
    dialog.setTargetFragment(this, type);
    dialog.show(fm, "");
  }

  //保存
  public void volleyPostSave(final String type) {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_SAVE_OR_RUN);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mId);
    //加班
    if (OVER.equalsIgnoreCase(mFrom)) {
      params.put("attendType", "overnew");
    }
    //外出
    if (OUT.equalsIgnoreCase(mFrom)) {
      params.put("attendType", "outnew");
      params.put("ifLaterWrite", mIfLaterWriter);//申请或补填
    }
    params.put("saveOrRun", type);
    params.put("totalDesc", metMianReasonCheckOver.getText().toString());

    MyUtils.showDialogLoading(getActivity());

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) {

        MyUtils.dismissDialog();
        try {
          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();

          switch (successType) {
            case "1":
              if (mcontent == null && TYPE_SAVE.equalsIgnoreCase(type)) {
                //添加保存
                ToastUtil.show(R.string.save_success);
                getActivity().setResult(Activity.RESULT_OK);
                if (!isSave) {
                  //第一次保存成功跳到列表,第二次保存不跳转
                  isSave = true;
                  //外出
                  if (OUT.equalsIgnoreCase(mFrom)) {
                    mcallBack.onRefresh(mId, mIfLaterWriter);//跳转到第二个tab页
                    mRgOut.setEnabled(false);//保存成功后不可编辑
                  }
                  //加班
                  if (OVER.equalsIgnoreCase(mFrom)) {
                    mcallBack.onRefresh(mId, "");//跳转到第二个tab页
                  }
                }
              } else {
                //修改保存或启动流程
                ToastUtil.show(R.string.success_operation);
                getActivity().setResult(Activity.RESULT_OK);
                getActivity().finish();
              }

              break;
            case "0":
              showErrorDialog(successsMessage.getMessage());
              break;
            default:
              ToastUtil.show(R.string.failure_operation);
              break;
          }
        } catch (Exception e) {
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }
    });
  }

  public boolean isCorrectInput() {
    // 验证文本信息
    String reasonString = metMianReasonCheckOver.getText().toString().trim();
    if (TextUtils.isEmpty(reasonString)) {
      Toast.makeText(getActivity(), R.string.no_content, Toast.LENGTH_SHORT).show();
      return false;
    }
    return true;
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (resultCode != Activity.RESULT_OK) return;

    if (requestCode == REQUEST_DELETE) {
      volleyPostDelete();
    }
    if (requestCode == REQUEST_SUBMIT) {
      volleyPostSave(TYPE_RUN);
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_REQUISITION_DELETE);
    HashMap<String, String> params = new HashMap<>();

    params.put("ids", mcontent.getAttendType() + "#" + mId);
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            ToastUtil.show(R.string.success_operation);
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.failure_operation);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.failure_operation);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  /**
   * TODO终止流程
   */
  private void interruptProcess() {
    MyUtils.showDialogLoading(getActivity());
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TASK_STOP);
    HashMap<String, String> params = new HashMap<>();

    params.put("runId", mcontent.getRunId());

    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);
          String successType = successsMessage.getResult();
          if (successType.equals("1")) {
            Toast.makeText(getActivity(), R.string.interruptSuccess, Toast.LENGTH_SHORT).show();
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            Toast.makeText(getActivity(), R.string.interruptFail, Toast.LENGTH_SHORT).show();
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          Toast.makeText(getActivity(), R.string.interruptFail, Toast.LENGTH_SHORT).show();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("VolleyError", arg0);
        Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
      }
    });
  }

  protected void showErrorDialog(String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()).setMessage(message)
        .setTitle("提示")
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {

          @Override public void onClick(DialogInterface dialog, int which) {
            // Auto-generated method stub

          }
        });
    builder.create().show();
  }

  public static CheckOutMainFragment newInstance(RequisitionSimpleOriginal content, String from,
      String ifAllowSupplement) {

    Bundle args = new Bundle();
    args.putSerializable(EXTRA_CONTENT, content);
    args.putString(EXTRA_FROM, from);
    args.putString(EXTRA_IFALLOWSUPPLEMENT, ifAllowSupplement);
    CheckOutMainFragment fragment = new CheckOutMainFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
